#!/usr/bin/env python
# -*- coding: utf-8 -*-

# var args = "ac=" + escape($.trim($account.val())) 
#           + "&un=" + escape($.trim($username.val())) 
#           + "&pwd=" + $.trim($password.val()) 
#           + "&pwd2=" + $.trim($password2.val()) 
#           + "&cd=" + $.trim($code.val()) 
#           + "&sc=" + $.trim($school.val());

import requests
import json

class Favor(object):
    
    ROOT_URL = r'http://campus.finance365.com/'
    REGISTER_URL = r'http://i.finance365.com/campususer/register'
    POST_URL = r'http://i.finance365.com/CampusUser/ToRegister'
    _LOGIN_URL = r'http://i.finance365.com/auth/login?ul=http%3a%2f%2fcampus.finance365.com%2fRematch%2fUserCenter%2f38&sc=campus'
    LOGIN_URL = r'http://i.finance365.com/Auth/ToLogin'
    # 日志
    DAILY_URL = ROOT_URL + r'/Rematch/PraiseDaily'

    def __init__(self):
        # register require
        self.__username = None
        self.__pwd = None
        self.__name = None
        self.__cd = ""
        self.__sc = None
        # login require
        self.__source = 'campus'
        self.__daily_no = None
        # self.__username
        # self.__pwd
        #
        # 赞日志
        self.__daily_count = 0

        self.__req = requests.Session() 
        self.__req.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36'
        try:
            self.__req.get(r'http://campus.finance365.com/Rematch/Index')
        except requests.exceptions.ConnectionError:
            print '联网失败，请检查网络 或者 查看是否该网站已死～～'
            exit()
        except :
            print "未知原因"
            exit()

    def login(self, username=None, password=None, daily_no=None):
        self.__req.get(Favor._LOGIN_URL)
        if username != None and password != None:
            self.__username = username
            self.__pwd = password

        if daily_no != None:
            self.__daily_no = daily_no

        payload = {
            'ac':self.__username,
            'pwd':self.__pwd,
            'sc':self.__source,
        }

        result = self.__req.post(Favor.LOGIN_URL, params=payload)
        
        jsondata = json.loads(result.text)

        print jsondata.get('Msg')

        is_logined = jsondata.get('Status')

        if is_logined == -1:
            exit()
        elif is_logined == 1:
            pass

        return result


    def register(self, username, pwd, name, school):
        '''注册,注册成功后保存用户名和密码'''
        self.__req.get(Favor.REGISTER_URL)
        self.__username = username
        self.__pwd = pwd
        self.__name = name
        self.__sc = school

        payload = {
            'ac':self.__username,
            'un':self.__name,
            'pwd':self.__pwd,
            'pwd2':self.__pwd,
            'cd':self.__cd,
            'sc':self.__sc,
        }

        result = self.__req.post(Favor.POST_URL, params=payload)
        
        jsondata = json.loads(result.text)
        
        is_registered = jsondata.get('Status')

        print jsondata.get('Msg')
        if is_registered == -5:
            exit()
        else:
            self.store_user()

        return result

    def store_user(self):
        with open('userlist', 'a+') as userlist:
            userlist.write(self.__username + ' ' +self.__pwd + '\n')

        return True

    def PraiseDaily(self, daily_no):
        self.__req.get(r'http://campus.finance365.com/Rematch/Index')
        payload = {'daily_no':daily_no}
        result = self.__req.post(Favor.DAILY_URL, params=payload)

        jsondata = json.loads(result.text)

        print jsondata.get('Msg')

        is_praised = jsondata.get('Status')
        if is_praised:
            self.__daily_count += 1
            self.Counseling()
        else:
            exit()

        return result

    def PraiseDaily_auto(self, daily_no):
        #self.__req.get(r'http://campus.finance365.com/Rematch/Index')
        payload = {'daily_no':daily_no}
        result = self.__req.post(Favor.DAILY_URL, params=payload)

        jsondata = json.loads(result.text)

        print jsondata.get('Msg')

        is_praised = jsondata.get('Status')
        if is_praised:
            self.__daily_count += 1
        #else:
        #    exit()


    def Counseling(self):
        if self.__daily_count == 0:
            daily_no = raw_input('请输入要赞日志的编号: ')
            try:
                self.__daily_no = int(daily_no)
            except ValueError:
                daily_no = raw_input('输入错误，可能包含非数字字符,请输入要赞日志的编号: ')
                try:
                    self.__daily_no = int(daily_no)
                except:
                    print '机会是留给会珍惜的人的！'
                    exit()
            self.PraiseDaily(self.__daily_no)
        else:
            print "你已赞过{count}篇日子".format(count=self.__daily_count)
            ask = raw_input("是否需要赞其他日志?(Y/NO)")
            if ask in ['Y', 'y', 'YES', 'yes', 'Yes']:

                daily_no = raw_input('请输入要赞日志的编号: ')
                try:
                    self.__daily_no = int(daily_no)
                except ValueError:
                    daily_no = raw_input('输入错误，可能包含非数字字符,请输入要赞日志的编号: ')
                    try:
                        self.__daily_no = int(daily_no)
                    except:
                        print '机会是留给会珍惜的人的！'
                        exit()
                self.PraiseDaily(self.__daily_no)
            else :
                exit()


    def run(self):
        username = raw_input("用户名(仅限邮箱): ")
        password = raw_input("密码: ")
        name = raw_input("姓名: ")
        school = raw_input("学校: ")
        self.register(username, password, name, school)
        self.login()
        self.Counseling()

if __name__ == '__main__':
    A = Favor()
    #A.register('76591712123@qq.com', '76591712123', '李琳', '西安交大')
    A.run()

